#include "../Lights.hlsl"
cbuffer PixelShaderConstantBuffer
{
	float4 eyePositionWorld;
	int4 lightsNumber; //directional,point,spot
	DirectionalLight directionalLights[100];
	PointLight pointLights[100];
	SpotLight spotLights[100];
};

Texture2D ambientMap:register(t0);
Texture2D diffuseMap:register(t1);
Texture2D specularMap:register(t2);

SamplerState anisotropicSamplerState : register(s0);

struct PixelInput
{
	float4 positionHomogeneous : SV_POSITION;
	float3 positionWorld : POSITION;
	float3 normalWorld : NORMAL;
	float2 textureCoordinate: TEXCOORD;
};

float4 main(PixelInput input) : SV_TARGET
{

	input.normalWorld = normalize(input.normalWorld);

	float3 surfaceToEyeDirection = normalize(eyePositionWorld.xyz - input.positionWorld.xyz);

	float4 ambient = float4(0.0f, 0.0f, 0.0f, 0.0f);
	float4 diffuse = float4(0.0f, 0.0f, 0.0f, 0.0f);
	float4 specular = float4(0.0f, 0.0f, 0.0f, 0.0f);

	Material material;
	material.ambient = ambientMap.Sample(anisotropicSamplerState, input.textureCoordinate);
	material.diffuse = diffuseMap.Sample(anisotropicSamplerState, input.textureCoordinate);
	material.specular = specularMap.Sample(anisotropicSamplerState, input.textureCoordinate);
	material.reflect = float4(0.0f, 0.0f, 0.0f, 0.0f);

	float4 tempAmbient, tempDiffuse, tempSpecular;

	for (int i = 0; i < lightsNumber.x; ++i)
	{
		ComputeDirectionalLight(material, directionalLights[i], input.normalWorld.xyz, surfaceToEyeDirection, tempAmbient, tempDiffuse, tempSpecular);
		ambient += tempAmbient;
		diffuse += tempDiffuse;
		specular += tempSpecular;
	}
	for (int j = 0; j < lightsNumber.y; ++j)
	{
		ComputePointLight(material, pointLights[j], input.positionWorld.xyz, input.normalWorld.xyz, surfaceToEyeDirection, tempAmbient, tempDiffuse, tempSpecular);
		ambient += tempAmbient;
		diffuse += tempDiffuse;
		specular += tempSpecular;
	}
	for (int k = 0; k < lightsNumber.z; ++k)
	{
		ComputeSpotLight(material, spotLights[k], input.positionWorld.xyz, input.normalWorld.xyz, surfaceToEyeDirection, tempAmbient, tempDiffuse, tempSpecular);
		ambient += tempAmbient;
		diffuse += tempDiffuse;
		specular += tempSpecular;
	}

	float4 result = ambient + diffuse + specular;
	result.a = material.diffuse.a; //Take alpha from diffuse material

	//result = float4(1.0f, 0.0f, 0.0f, 0.0f);

	return result;
}